<?php
/**
 * Created by PhpStorm.
 * User: xiaoqiang
 * Date: 16-3-6
 * Time: 下午7:09
 */

namespace ElasticSearch;


class EsDocument extends EsBase
{
    /**
     * 增加数据(可单条，可批量)
     * @param $data
     * @param string $field
     * @return mixed|string
     */
    public function add($data, $field = "id")
    {
        if (!is_array($data)) {
            return array();
        }
        if (!EsTools::isMultiArray($data)) {
            $data = [$data];
        }
        $contents = "";
        foreach ($data as $d) {
            $contents .= json_encode([
                    "create" => [
                        "_index" => $this->index,
                        "_type" => $this->type,
                        "_id" => isset($d[$field]) ? $d[$field] : NULL
                    ]
                ]) . "\n";
            unset($d[$field]);
            $contents .= json_encode($d) . "\n";
        }
        $result = $this->bulk($contents);
        return $result;
    }

    /**
     * 修改数据(可单条，可批量)。
     * @param $data
     * @param string $field
     * @return mixed|string
     */
    public function update($data, $field = "id")
    {
        if (!EsTools::isMultiArray($data)) {
            $data = array($data);
        }
        $contents = "";
        foreach ($data as $d) {
            $contents .= json_encode([
                    "update" => [
                        "_index" => $this->index,
                        "_type" => $this->type,
                        "_id" => $d[$field]
                    ]
                ]) . "\n";
            unset($d[$field]);
            $contents .= json_encode(["doc" => $d]) . "\n";
        }
        $result = $this->bulk($contents);
        return $result;
    }


    /**
     * 单条替换或增加文档(若文档存在，就替换，若不在则插入)
     * @param $data
     * @param string $field
     * @return mixed|string
     */
    public function replace($data, $field = "id")
    {
        if (!EsTools::isMultiArray($data)) {
            $data = array($data);
        }
        $info = array();
        $errors = 0;
        $zip = 0;
        foreach ($data as $d) {
            $id = $d[$field];
            $uri = EsTools::baseUri($this->hosts, $this->index, $this->type, $id);;
            $res = EsHttp::put($uri, $d);
            $errors += $res["_shards"]["failed"];
            $zip = $res['zip'];
            $info[] = $res;
        }
        $result = [
            "errors" => $errors,
            "items" => $info,
            "zip" => $zip
        ];
        return $result;
    }

    /**
     * 删除数据
     * @param $data
     * @return mixed|string
     */
    public function delete($data)
    {
        if (is_array($data)) {
            $contents = "";
            foreach ($data as $d) {
                $contents .= json_encode([
                        "delete" => [
                            "_index" => $this->index,
                            "_type" => $this->type,
                            "_id" => $d
                        ]
                    ]) . "\n";
            }
            $result = $this->bulk($contents);
        } else {
            $uri = EsTools::baseUri($this->hosts, $this->index, $this->type, $data);;
            $result = EsHttp::delete($uri);
        }
        return $result;
    }

    /**
     * 根据ID获取文档信息(单个索引单个文档中)
     * @param string|array $data 可以是单个ID，也可以是ID数组
     * @param string $field 获取文档的指定字段信息
     * @return mixed|string
     */
    public function get($data, $field = "*")
    {
        if (is_array($data)) {
            $primaryKey = "_mget";
            if ($field != "*") {
                $primaryKey .= "?" . "_source=" . $field;;
            }
            $uri = EsTools::baseUri($this->hosts, $this->index, $this->type, $primaryKey);
            $jsonStr = json_encode([
                "ids" => $data
            ]);
            $result = EsHttp::get($uri, $jsonStr);
        } else {
            if ($field != "*") {
                $data .= "?" . "_source=" . $field;
            }
            $uri = EsTools::baseUri($this->hosts, $this->index, $this->type, $data);
            $result = EsHttp::get($uri);
        }
        return $result;
    }

    /**
     * 通过数组的形式在从多个索引或多个类型里面获取文档
     * @param $data
     * @return mixed|string
    [
     * [
     * "_index" : "website",
     * "_type" :  "blog",
     * "_id" :    2
     * ],
     * [
     * "_index" : "website",
     * "_type" :  "pageviews",
     * "_id" :    1,
     * "_source": "views"
     * ]
     * ]
     */
    public function mGet($data)
    {
        $data = array(
            "docs" => $data
        );
        $jsonStr = json_encode($data);
        $uri = EsTools::specialUri($this->hosts, "_mget");
        return EsHttp::get($uri, $jsonStr);
    }


    /**
     * 检查文档是否存在
     * @param $id
     * @return mixed|string
     */
    public function exists($id)
    {
        $uri = EsTools::baseUri($this->hosts, $this->index, $this->type, $id);
        $result = EsHttp::head($uri);
        if (stripos($result, "200") === false) {
            return false;
        }
        return true;
    }
}